package com.bdi.mqtt_broker.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bdi.mqtt_broker.constant.Constants;
import com.bdi.mqtt_broker.model.SessionStore;
import com.bdi.mqtt_broker.service.ISessionStoreService;
import com.bdi.mqtt_broker.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @author WangNing yogehaoren@gmial.com <br>
 * @since 1.0
 */
@Service
public class ISessionStoreServiceImpl implements ISessionStoreService {

    @Autowired
    RedisService redisService;

    @Override
    public void put(String clientId, SessionStore sessionStore) {

        redisService.set(Constants.SESSION_CACHE_PRE + clientId, SessionStore.toJsonString(sessionStore));

    }

    @Override
    public SessionStore get(String clientId) {
        String jsonObject = redisService.get(Constants.SESSION_CACHE_PRE + clientId);
        if(StringUtils.hasText(jsonObject)){

            return JSONObject.toJavaObject(JSON.parseObject(jsonObject), SessionStore.class);

        }
        return null;
    }

    @Override
    public boolean containsKey(String clientId) {
        return redisService.exists(Constants.SESSION_CACHE_PRE + clientId);
    }

    @Override
    public void remove(String clientId) {
        redisService.del(Constants.SESSION_CACHE_PRE + clientId);
    }
}
